import 'package:flutter/material.dart';
import 'package:rxdart/rxdart.dart';
import 'package:wallpaper/api/mohu.dart';
import 'package:wallpaper/components/appbar_base.dart';
import 'package:wallpaper/components/empty.dart';
import 'package:wallpaper/components/images/image_load.dart';
import 'package:wallpaper/components/images/image_view.dart';
import 'package:wallpaper/model/image_base.dart';
import 'package:wallpaper/model/options_base.dart';

class MohuImgs extends StatefulWidget {
  final String type;
  final String title;
  const MohuImgs({super.key, required this.type, required this.title});

  @override
  State<MohuImgs> createState() => _MohuImgsState();
}

class _MohuImgsState extends State<MohuImgs> {
  List<ImageBase> imgs = [];
  Set<String> imgUrls = <String>{};
  bool loading = false;
  // 横屏壁纸为主
  List pcs = ['pc', 'img1', 'img2', 'gqbz', 'cat'];
  final ScrollController _scrollController = ScrollController();

  void getImgs() async {
    setState(() {
      loading = true;
    });
    if (!mounted) return;
    var res = await mohuImgsApi(id: widget.type);
    if (res.data['code'] == 200 || res.data['code'] == '200') {
      for (var i = 0; i < res.data['pic'].length; i++) {
        ImageBase img = ImageBase(
            smallPath: res.data['pic'][i],
            largePath: res.data['pic'][i].replaceAll('mw690', 'large'),
            tags: '');
        // 判断是否存在
        if (!imgUrls.contains(img.smallPath)) {
          setState(() {
            imgUrls.add(img.smallPath);
            imgs.add(img);
          });
        }
      }
    }
    setState(() {
      loading = false;
    });
  }

  final _throttle = PublishSubject<void>();
  @override
  void initState() {
    super.initState();
    getImgs();
    _scrollController.addListener(() {
      if (_scrollController.position.pixels >=
          _scrollController.position.maxScrollExtent - 200) {
        _throttle.add(null);
      }
    });
    _throttle.throttleTime(const Duration(milliseconds: 300)).listen((_) {
      getImgs();
    });
  }

  @override
  Widget build(BuildContext context) {
    return RefreshIndicator(
        child: Scaffold(
            appBar: AppbarBase(title: widget.title),
            body: loading && imgs.isEmpty
                ? Center(child: CircularProgressIndicator())
                : Padding(
                    padding: EdgeInsets.all(1),
                    child: imgs.isEmpty
                        ? Empty()
                        : GridView.builder(
                            itemCount: imgs.length,
                            controller: _scrollController,
                            gridDelegate:
                                SliverGridDelegateWithFixedCrossAxisCount(
                              crossAxisCount:
                                  OptionsBase().imageColumns(context),
                              childAspectRatio:
                                  pcs.contains(widget.type) ? 1.5 : 0.7,
                            ),
                            itemBuilder: (context, index) {
                              return buildItem(context, index);
                            },
                          ),
                  )),
        onRefresh: () {
          setState(() {
            imgs.clear();
            imgUrls.clear();
            getImgs();
          });
          return Future.delayed(
              Duration(milliseconds: OptionsBase().refreshTime));
        });
  }

  Widget buildItem(context, int index) {
    return Container(
      margin: EdgeInsets.all(OptionsBase().padding / 2),
      decoration: BoxDecoration(
          color: Theme.of(context).colorScheme.secondary,
          borderRadius: BorderRadius.circular(10),
          boxShadow: [
            BoxShadow(
              color: Theme.of(context).colorScheme.shadow,
              offset: Offset(1, 2),
              blurRadius: 2,
            ),
          ]),
      child: ClipRRect(
        borderRadius: BorderRadius.circular(5),
        child: GestureDetector(
          onTap: () {
            Navigator.push(
                context,
                MaterialPageRoute(
                    builder: (context) => ImageView(
                          images: imgs,
                          selectedIndex: index,
                          resetGetdata: () {},
                        )));
          },
          child: Stack(alignment: Alignment.bottomLeft, children: [
            SizedBox(
                width: double.infinity,
                height: double.infinity,
                child: ImageLoad(imageUrl: imgs[index].smallPath)),
            Container(
                color: const Color.fromARGB(24, 158, 158, 158),
                width: double.infinity,
                height: imgs[index].tags == "" ? 0 : 20,
                child: Padding(
                  padding: const EdgeInsets.only(left: 5, right: 5),
                  child: Text(
                    imgs[index].tags,
                    overflow: TextOverflow.ellipsis,
                    maxLines: 1,
                    style: TextStyle(color: Colors.white, fontSize: 13),
                  ),
                )),
          ]),
        ),
      ),
    );
  }
}
